<?php
/**
 * @return
 * @author 朱乐斌
 * @date
 */

namespace app\api\controller;

use app\api\model\SendSmsCodeModel;
use app\api\model\UserGxModel;
use app\api\validate\UserValidate;
use Firebase\JWT\JWT;
use think\Exception;

class Login extends Base
{

    protected $key = 'zlb';



    // 使用验证码登录
    public function codeLogin()
    {
        // 接收数据
        $data = $this->request->post();
        try {
            // 查询用户是否注册
            $user = new UserGxModel();                                                                                                                           new UserGxModel();
            $user = $user->where('phone', $data['phone'])->find();
            if (empty($user)) $this->error('账号没用注册');
            // 实例化验证码模型查询验证码是否一致
            $code = new SendSmsCodeModel();
            $code = $code->where('phone', $data['phone'])->order('id', 'desc')->find();
            if ($code['code'] != $data['code']) return errMsg('验证码错误');
            if ($code['code'] == $data['code']) {
                // 登录成功生成JWT
                $payload = [
                    // 签发人
                    'iss' => "zlb",
                    // 签发时间
                    'iat' => time(),
                    // 过期时间
                    'exp' => time() + 8200,
                    // 自定义数据
                    'data' => [
                        'phone' => $user['phone'],
                    ]
                ];
                $jwt = JWT::encode($payload, $this->key, 'HS256');
                // 删除code
                $code->where('phone', $data['phone'])->delete();
                $this->success('登录成功', ['token' => $jwt]);
            }
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * @note 密码登录
     */
    public function Login()
    {
        // 接收数据
        $data = $this->request->post();
        try {
            // 验证数据
            validate(UserValidate::class)->scene('login')->check($data);
            // 查询数据库里面有没有手机号
            $user = UserGxModel::where('phone', $data['phone'])->find();
            if ($user == null) return errMsg('该手机号未注册!');
            // 判断用户的密码是否正确
            if (md5($data['password']) == $user['password']) {
                // 登录成功生成JWT
                $payload = [
                    // 签发人
                    'iss' => "zlb",
                    // 签发时间
                    'iat' => time(),
                    // 过期时间
                    'exp' => time() + 7200,
                    // 自定义数据
                    'data' => [
                        'phone' => $user['phone'],
                    ]
                ];

                $jwt = JWT::encode($payload, $this->key, 'HS256');
                return succMsg(['token' => $jwt]);
            } else {
                return errMsg('密码错误!');
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }

    // 注册
    public function register()
    {
        // 接收参数
        $data = $this->request->param();
        $image = "http://s2mgl5zzu.bkt.clouddn.com/%E5%A4%B4%E5%83%8F.webp";
        try {
            // 验证器验证(验证数据是否正确)
            validate(UserValidate::class)->scene('register')->check($data);
            $name = $data['type'] == 1 ? '个人用户_' : '企业用户_';
            $phoneNumber = $data['phone'];
            // 查询手机号是否注册过
            $model = new UserGxModel();
            $model = $model->where('phone', $phoneNumber)->find();
            if ($model != null) return errMsg('该手机号已注册,请直接登录');
            // 验证code是否正确
            $code = new SendSmsCodeModel();
            $code = $code->where('phone', $phoneNumber)->order('id', 'desc')->value('code');
            if ($code == null) return errMsg('请获取验证码');
            if ($code != $data['code']) return errMsg('验证码错误!');
            // 验证两次密码是否相同
            if ($data['password'] != $data['password2']) return errMsg('两次密码不相同请重新输入');
            // 密码加密存入数据库
            $userInfo = [
                'name' => $name . substr($phoneNumber, -4),
                'phone' => $phoneNumber,
                'password' => md5($data['password']),
                'type' => $data['type'],
                'image' => $image
            ];
            // 添加用户信息
            $userModel = new UserGxModel();
            if (!$userModel->save($userInfo)) return errMsg('注册失败');
            $code = $code->where('phone',$phoneNumber)->delete();
            return succMsg([], 1, '注册成功!');
        } catch (\Exception $e) {
            return errMsg($e->getMessage());
        }
    }

    // 获取短信验证码
    public function sendSmsCode()
    {
        // 接收手机号
        $phone = $this->request->post('phone/s');
        try {
            // 验证器验证(验证数据是否正确)
            validate(UserValidate::class)->scene('sms')->check(['phone' => $phone]);
            // 生成验证码
            $code = mt_rand(100000, 999999);
            // 存入数据库
            $codeModel = new SendSmsCodeModel();
            $codeModel = $codeModel->save([
                'phone' => $phone,
                'code' => $code
            ]);
            // 判断是否存入数据库
            if (!$codeModel) return errMsg('验证码发送失败');
            // 发送成功
            return succMsg(['code' => $code, 1, '发送成功!']);
        } catch (\Exception $e) {
            return errMsg($e->getMessage());
        }
    }


    // 忘记密码
    public function modifyPassword()
    {
        // 接收数据
        $data = $this->request->post();
        try {
            // 验证手机号是否正确
            validate(UserValidate::class)->scene('modifyPassword')->check($data);
            // 判断接收账号是否注册过
            $user = UserGxModel::where('phone',$data['phone'])->value('phone');
            if (empty($user)) return errMsg('该账号未注册');
            // 查询验证码
            $sendCode = SendSmsCodeModel::where('phone','=',$data['phone'])->field('phone,code')->order('id desc')->find();
            // 验证
            if (empty($sendCode)) return errMsg('请获取验证码');
            if ($sendCode['code'] != $data['code']) return errMsg('验证码错误');
            // 判断两次密码是否一致
            if ($data['password'] !== $data['password2']) return errMsg('二次密码不一样');
            // 通过存储数据
            $user = $user->where('phone','=',$user)->find();
            $date = [
                'password' =>  md5($data['password'])
            ];
            if ($user->save($date)) return succMsg(array(),'修改成功');
        }catch (\Exception $e){
            return errMsg($e->getMessage());
        }
    }



}